package com.baway.home.vm

import androidx.lifecycle.MutableLiveData
import com.baway.common.entity.NoticeEntity
import com.baway.common.vm.BaseViewModel
import com.baway.db.entity.UserInfoEntity
import com.baway.home.model.HomeRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.lang.reflect.Method
import javax.inject.Inject

/**
 * Author: Jason Zhang
 * Date: 2025/8/18
 * Desc: HomeViewModel
 * 协程调度器Dispatchers
 * Dispatchers.IO      在子线程中调度（使用线程池，其中线程数64个），适用于耗时多任务场景
 * Dispatchers.Main    在主线中调度（在UI线程，只有1个），适用于UI更新
 * Dispatchers.Default  取决于调用方（固定数量线程池，其中线程数CPU个数+1），适用于少量任务复杂计算
 * Dispatchers.Unconfined 没有限制（没有限制线程数量）
 */

@HiltViewModel
class HomeViewModel @Inject constructor(private val repo: HomeRepository): BaseViewModel(){

    //定义LiveData缓存数据
    val mSuccess = MutableLiveData<List<NoticeEntity>>()
    val mUserInfo= MutableLiveData<UserInfoEntity>()

    //模拟10条公共数据
    private var tempNoticeData = arrayListOf(
        NoticeEntity("小区公告，七夕节快乐！！", "2025-08-28","园区公告"),
        NoticeEntity("小区公告，七夕节快乐！！", "2025-08-27","维修公告"),
        NoticeEntity("活动公告，七夕节快乐！！", "2025-08-28","活动公告"),
        NoticeEntity("七夕节快乐！！", "2025-08-26","大会公告"),
        NoticeEntity("大会公告，七夕节快乐！！", "2025-08-28","停水公告"),
        NoticeEntity("七夕节快乐！！", "2025-08-25","来访公告"),
        NoticeEntity("停电公告，七夕节快乐！！", "2025-08-28","停电公告"),
        NoticeEntity("七夕节快乐！！", "2025-08-21","小区公告"),
        NoticeEntity("物业将于29日在小区广场，举办七夕节！！", "2025-08-20","活动公告"),
        NoticeEntity("祝愿小区所有女神，七夕节快乐！！", "2025-08-23","七夕活动公告"),
    )


    fun loadNoticeData(pageIndex: Int, pageSize: Int){
        mViewModelScope.launch(mDispatcher) {
            val (code, data, message) = repo.loadNoticeData(pageIndex, pageSize)
            if (code == 200){
                data.map {
                    val index = Math.random() * 10
                    val tempEntity = tempNoticeData[index.toInt()]
                    it.title = tempEntity.title
                    it.content = tempEntity.content
                    it.publishTime = tempEntity.publishTime
                }
                mSuccess.postValue(data)
            } else {
                mError.postValue(message)
            }
        }
    }

    fun queryUserInfoFormRoom(userId: Int){
        mViewModelScope.launch(mDispatcher) {
            val userInfo = repo.queryUserInfo(userId)
            mUserInfo.postValue(userInfo)
        }


    }









}